import { loginByUsername, logout } from '@/api/login'
import { getName, getIntroduction, getRoles, setName, setIntroduction, setRoles, removeAuth } from '@/utils/auth'

const user = {
  state: {
    name: getName(), // 姓名
    introduction: getIntroduction(), // xxx管理员
    roles: getRoles() // 权限
  },
  mutations: {
    SET_NAME: (state, name) => {
      state.name = name
    },
    SET_INTRODUCTION: (state, introduction) => {
      state.introduction = introduction
    },
    SET_ROLES: (state, roles) => {
      state.roles = [roles]
    }
  },
  actions: {
    LoginByUsername ({ commit }, userInfo) {
      const username = userInfo.userName.trim()
      return new Promise((resolve, reject) => {
        loginByUsername(username, userInfo.password, userInfo.captcha).then(response => {
          const data = response.data
          commit('SET_NAME', data.name)
          commit('SET_INTRODUCTION', data.introduction)
          commit('SET_ROLES', data.role)
          setName(data.name)
          setIntroduction(data.introduction)
          setRoles(data.role)
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    },
    LogOut ({ commit, state }) {
      return new Promise((resolve, reject) => {
        logout(state.token).then(() => {
          commit('SET_NAME', '')
          commit('SET_INTRODUCTION', '')
          commit('SET_ROLES', [])
          removeAuth()
          resolve()
        }).catch(error => {
          reject(error)
        })
      })
    }
  }
}

export default user
